package com.zlht.controller;

import com.zlht.entity.Promotion;
import com.zlht.entity.Store;
import com.zlht.service.PromotionService;
import com.zlht.service.imp.PromotionServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/promotion")
public class PromotionServlet extends HttpServlet {

    PromotionService promotionService = new PromotionServiceImp();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        switch (method) {
            case "list":
                req.setAttribute("list", this.promotionService.list());
                req.getRequestDispatcher("promotionmanager.jsp").forward(req, resp);
                break;
            case "search":
                String key = req.getParameter("key");
                String value = req.getParameter("value");
                req.setAttribute("list",this.promotionService.search(key ,value));
                req.getRequestDispatcher("promotionmanager.jsp").forward(req, resp);
                break;
            case "save":
                String name = req.getParameter("name");
                String description = req.getParameter("description");
                String start = req.getParameter("start");
                String end = req.getParameter("end");
                String discount = req.getParameter("discount");
                this.promotionService.save(new Promotion(name,description,start,end,discount));
                resp.sendRedirect("/promotion?method=list");
                break;
            case "update":
                String idStr = req.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                name = req.getParameter("name");
                description = req.getParameter("description");
                start = req.getParameter("start");
                end = req.getParameter("end");
                discount = req.getParameter("discount");
                this.promotionService.update(new Promotion(id,name,description,start,end,discount));
                resp.sendRedirect("/promotion?method=list");
                break;
            case "delete":
                idStr = req.getParameter("id");
                id = Integer.parseInt(idStr);
                this.promotionService.delete(id);
                resp.sendRedirect("/promotion?method=list");
                break;
        }
    }
}
